package com.ruoyi.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.URL;

@Service
public class DashScopeService {

    @Value("${dashscope.api.key}")
    private String apiKey;

    private final RestTemplate restTemplate = new RestTemplate();

    public String generateBackground(String baseImageUrl, String refImageUrl, String refPrompt) {
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/background-generation/generation/";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("X-DashScope-Async", "enable");
        headers.set("Authorization", "Bearer " + apiKey);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "wanx-background-generation-v2");

        // 构建input部分
        Map<String, Object> input = new HashMap<>();
        input.put("base_image_url", baseImageUrl);
        input.put("ref_image_url", refImageUrl);
        input.put("ref_prompt", refPrompt);

        // 构建reference_edge部分
        Map<String, Object> referenceEdge = new HashMap<>();

        List<String> foregroundEdge = new ArrayList<>();
        foregroundEdge.add("http://sushyyr85.hb-bkt.clouddn.com/50850da8-e485-48f9-90a2-1bcb5cca503c.png");
        foregroundEdge.add("http://sushyyr85.hb-bkt.clouddn.com/8222c7e6-7af4-4a5b-a6d9-b4efd72d51d5.png");
        referenceEdge.put("foreground_edge", foregroundEdge);
        // 背景
        List<String> backgroundEdge = new ArrayList<>();
        backgroundEdge.add("http://sushyyr85.hb-bkt.clouddn.com/aa42e347-cdd0-4510-8daa-7dce570f13f7.png");
        referenceEdge.put("background_edge", backgroundEdge);

        List<String> foregroundEdgePrompt = new ArrayList<>();
        foregroundEdgePrompt.add("粉色桃花");
        foregroundEdgePrompt.add("可爱小狗");
        referenceEdge.put("foreground_edge_prompt", foregroundEdgePrompt);

        List<String> backgroundEdgePrompt = new ArrayList<>();
        backgroundEdgePrompt.add("树叶");
        referenceEdge.put("background_edge_prompt", backgroundEdgePrompt);

        input.put("reference_edge", referenceEdge);
        requestBody.put("input", input);

        // 构建parameters部分
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("model_version", "v3");
        parameters.put("n", 1);
        parameters.put("ref_prompt_weight", 0.5);
        parameters.put("noise_level", 300);
        requestBody.put("parameters", parameters);

        // 发送请求
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);

        // 处理响应
        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            // 由于使用了异步API，这里返回的是任务ID
            Map<String, Object> responseBody = response.getBody();
            String taskId = responseBody.get("output").toString();
            Pattern pattern = Pattern.compile("task_id=([a-fA-F0-9\\-]+)");
            Matcher matcher = pattern.matcher(taskId);
            String id = null;
            if (matcher.find()) {
                id = matcher.group(1);
                System.out.println("taskId=" + id); // 输出结果
            } else {
                System.out.println("未找到 task_id");
            }
            return id;
        } else {
            throw new RuntimeException("调用DashScope API失败");
        }
    }


    // 查询异步任务结果
    public String queryTaskResult(String taskId) {
        try {
            URL url = new URL("https://dashscope.aliyuncs.com/api/v1/tasks/" + taskId);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求头和参数
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", apiKey);
            conn.setConnectTimeout(5000);

            // 获取响应
            int status = conn.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 使用 Jackson 解析 JSON
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(response.toString());
                JsonNode resultsNode = rootNode.path("output").path("results");
                if (!resultsNode.isMissingNode() && resultsNode.isArray() && resultsNode.size() > 0) {
                    JsonNode firstResult = resultsNode.get(0);
                    System.out.println(firstResult);
                    return firstResult.path("url").asText();
                }
            } else {
                System.out.println("请求失败，状态码: " + status);
            }
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




}
